package com.chuanjiabao.wisdom.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.GeneratePresignedUrlRequest;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.adapter.SecretMonthAdapter;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.AuthCallbackBean;
import com.chuanjiabao.wisdom.bean.FamilyFileTotalBean;
import com.chuanjiabao.wisdom.bean.FamilyResCallbackBean;
import com.chuanjiabao.wisdom.bean.ImageBean;
import com.chuanjiabao.wisdom.databinding.ActivitySecretResBinding;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.listener.RxObserver;
import com.chuanjiabao.wisdom.ui.BaseActivity;
import com.chuanjiabao.wisdom.util.BHThreadPool;
import com.chuanjiabao.wisdom.util.DropPopWindowUtils;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.TimeHelper;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.chuanjiabao.wisdom.util.dialog.DowloadDialog;
import com.chuanjiabao.wisdom.util.dialog.HintDeleteDialog;
import com.chuanjiabao.wisdom.util.dialog.ShareDialog;
import com.luck.picture.lib.permissions.RxPermissions;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;
import com.lzy.okgo.utils.OkLogger;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static com.alibaba.sdk.android.oss.common.HttpMethod.GET;
import static com.chuanjiabao.wisdom.bean.Constants.REQUEST_CODE_COPYREASION;

public class SecretResActivity extends BaseActivity {

    ActivitySecretResBinding binding;
    boolean isSelect = false;
    int pos = 0, p = 1;
    String strs = "", type = "", bucketName = "";

    OSSClient oss;
    List<FamilyResCallbackBean.DataBeanX.DataBean> listDataSecond = new ArrayList<>();
    Map<String, List<FamilyResCallbackBean.DataBeanX.DataBean>> maps = new HashMap<>();
    List<ImageBean> listItemLocations = new ArrayList<>();
    List<String> months = new ArrayList<>();
    SecretMonthAdapter monthAdapter;

    List<String> fileIds = new ArrayList<>();
    List<String> fileIdsSecond = new ArrayList<>();

    //图片/视频/文本
    private String photoUrl = "", photoHint = "所有图片";
    private String videoUrl = "", videoHint = "所有视频";
    private String textUrl = "", textHint = "文本";
    private DowloadDialog mDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_secret_res);
        binding.setActivity(this);
        initView();
    }

    private void initView() {
        binding.rightText.setOnClickListener(this);
        binding.ivModuleDelete.setOnClickListener(this);
        binding.tvModuleCheck.setOnClickListener(this);
        binding.llModuleShare.setOnClickListener(this);
        binding.rlModuleFinish.setOnClickListener(this);
        binding.ivModuleClock.setOnClickListener(this);
        if (oss == null) getAuth();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivModuleClock:
                strs = "";
                if (fileIds.size() != 0) {
                    for (String str : fileIds) {
                        //noinspection StringConcatenationInLoop
                        strs += str + ",";
                    }

                    new HintDeleteDialog(this)
                            .setTitle("添加相册")
                            .setContent(fileIds.size() + "项文件添加到相册")
                            .setYes("确认添加")
                            .setOnBHClickListener(new OnBHClickListener() {
                                @Override
                                public void onConfirmClick() {
                                    secretToHome(strs.substring(0, strs.length() - 1));
                                }
                            })
                            .show();
                } else {
                    ToastUtil.showToast("请选择要转移的文件！");
                }
                break;
            case R.id.llModuleShare:
                if (fileIds.size() != 1) {
                    ToastUtil.showToast("请选择单个图片或视频文件！");
                    return;
                }

                if (listItemLocations.get(0).getUrl() == null) {
                    ToastUtil.showToast("请选择单个图片或视频文件！");
                    return;
                }

                new RxPermissions(this)
                        .request(
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                        ).subscribe(new RxObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (!aBoolean) {
                            ToastUtil.showToast(R.string.picture_jurisdiction);
                            return;
                        }

                        ShareDialog dialog = new ShareDialog(
                                SecretResActivity.this,
                                listItemLocations.get(0).getType() == 1 ? "image" : "video");
                        dialog.show();
                        dialog.setOnShareStypeClickListener(style -> {
                            ImageBean bean = listItemLocations.get(0);
                            switch (style) {
                                case "Wx":
                                    new ShareAction(SecretResActivity.this)
                                            .setPlatform(SHARE_MEDIA.WEIXIN)
                                            .withText("河南传家宝")
                                            .withMedia(new UMImage(SecretResActivity.this, bean.getUrl()))
                                            .share();
                                    break;
                                case "QQ":
                                    new ShareAction(SecretResActivity.this)
                                            .setPlatform(SHARE_MEDIA.QQ)
                                            .withText("河南传家宝")
                                            .withMedia(new UMImage(SecretResActivity.this, bean.getUrl()))
                                            .share();
                                    break;
                                case "save":
                                    downloadFile(bean.getUrl(), bean.getType() == 1 ? "image" : "video");
                                    break;
                            }
                        });
                    }
                });
                break;
            case R.id.rightText:
                if (!isSelect) {
                    isSelect = true;
                    for (String str : months) {
                        monthAdapter.setCheckBoxStatus(isSelect, pos++);
                        List<FamilyResCallbackBean.DataBeanX.DataBean> items = maps.get(str);
                        for (FamilyResCallbackBean.DataBeanX.DataBean item: items) item.setChecked(false);
                    }
                    binding.rightText.setText("取消");

                    fileIds.clear();
                    listItemLocations.clear();
                } else {
                    isSelect = false;
                    for (String str : months) {
                        monthAdapter.setCheckBoxStatus(isSelect, pos++);
                    }
                    binding.rightText.setText("选择");
                }
                break;
            case R.id.ivModuleDelete:
                //先释放资源
                strs = "";
                if (fileIds.size() != 0) {
                    for (String str : fileIds) {
                        //noinspection StringConcatenationInLoop
                        strs += str + ",";
                    }

                    new HintDeleteDialog(this)
                            .setTitle("删除文件")
                            .setContent("是否删除" + fileIds.size() + "项文件")
                            .setYes("确认删除")
                            .setOnBHClickListener(new OnBHClickListener() {
                                @Override
                                public void onConfirmClick() {
                                    deleteSecretFile(strs.substring(0, strs.length() - 1));
                                }
                            })
                            .show();
                } else {
                    ToastUtil.showToast("请选择要删除的文件！");
                }
                break;
            case R.id.tvModuleCheck:
                DropPopWindowUtils.showDrop(
                        SecretResActivity.this,
                        binding.tvModuleCheck,
                        photoUrl, videoUrl, textUrl, photoHint, videoHint, textHint,
                        this::allClick
                );
                break;
            case R.id.rlModuleFinish:
                finish();
                break;
        }
    }

    public void allClick(String type) {
        p = 1;
        maps.clear();
        months.clear();
        this.type = type;
        if (TextUtils.equals("0", type)) this.type = "";
        getSecretFiles();
    }

    public void getAuth() {
        HTTPAPI.getInstance().getAuth(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("获取私密授权成功" + s);
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(SecretResActivity.this, s);
                } else {
                    final AuthCallbackBean bean = GsonUtil.GsonToBean(s, AuthCallbackBean.class);
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(
                                    bean.getData().getAccessKeyId(),
                                    bean.getData().getAccessKeySecret(),
                                    bean.getData().getSecurityToken()) {
                                @Override
                                public OSSFederationToken getFederationToken() {
                                    return super.getFederationToken();
                                }
                            };
                            OSSLog.enableLog();
                            oss = new OSSClient(SecretResActivity.this, "https://" + bean.getData().getEndPoint(),
                                    credentialProvider, FApplication.getInstance().getClientConfiguration());
                            handler.sendEmptyMessage(REQUEST_CODE_COPYREASION);
                        }
                    };
                    BHThreadPool.getInstance().executeTask(runnable);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int code = msg.what;
            if (code == REQUEST_CODE_COPYREASION) {
                getSecretFileTotal();
            }
        }
    };

    public void initRecycler() {
        monthAdapter = new SecretMonthAdapter(SecretResActivity.this, months, maps, true, true);
        binding.recycler.setLayoutManager(new LinearLayoutManager(SecretResActivity.this));
        binding.recycler.setItemAnimator(new DefaultItemAnimator());
        ((SimpleItemAnimator) binding.recycler.getItemAnimator()).setSupportsChangeAnimations(false);
        binding.recycler.setAdapter(monthAdapter);
        monthAdapter.setOnThirdClickListener((first, second, third, url) -> {
            if (!fileIds.contains(second + "")) {
                fileIds.add(second + "");
                listItemLocations.add(new ImageBean(first, second, third, url));
            } else {
                fileIdsSecond = fileIds;
                fileIdsSecond.remove(second + "");
                fileIds = fileIdsSecond;

                List<Integer> indexList = new ArrayList<>();
                for (ImageBean iv : listItemLocations) {
                    if (iv.getFirst() == first && iv.getSecond() == second) {
                        indexList.add(listItemLocations.indexOf(iv));
                    }
                }

                for (Integer item : indexList) {
                    listItemLocations.remove(item.intValue());
                }
            }
        });

        binding.refreshLayout.setOnRefreshListener(refreshlayout -> {
            p = 1;
            maps.clear();
            months.clear();
            fileIds.clear();
            listItemLocations.clear();
            getSecretFiles();
        });

        binding.refreshLayout.setOnLoadMoreListener(refreshlayout -> getSecretFiles());

        binding.refreshLayout.autoRefresh();
    }


    public void getSecretFiles() {
        HTTPAPI.getInstance().getSecretFiles(p++ + "", type, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                binding.refreshLayout.finishLoadMore();
                binding.refreshLayout.finishRefresh();
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(SecretResActivity.this, s);
                } else {
                    FamilyResCallbackBean listB = GsonUtil.GsonToBean(s, FamilyResCallbackBean.class);
                    listDataSecond = listB.getData().getData();
                    if (listDataSecond.size() == 0) {
                        ToastUtil.showToast("暂无更多数据");
                    } else {
                        for (FamilyResCallbackBean.DataBeanX.DataBean dataBean : listDataSecond) {
                            String createTime = dataBean.getCreate_time();
                            String dateNow = TimeHelper.getInstance().getNowTime("yyyy年MM月dd日");
                            String m = TimeHelper.getInstance()
                                    .stringToString(
                                            "yyyy-MM-dd HH:mm:ss",
                                            "yyyy年MM月dd日",
                                            createTime
                                    );

                            if (TextUtils.equals(dateNow, m)) {
                                m = "今天";
                            } else if (TextUtils.equals(
                                    dateNow.substring(0, 4),
                                    m.substring(0, 4)
                            )) {
                                m = TimeHelper.getInstance()
                                        .stringToString(
                                                "yyyy-MM-dd HH:mm:ss",
                                                "M月dd日",
                                                createTime
                                        );
                            }

                            bucketName = dataBean.getFile_bucket();
                            LogUtil.e("文件的filebucket-->" + bucketName);
                            if (1 == dataBean.getFile_type()) {
                                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                                        dataBean.getFile_bucket(),
                                        dataBean.getFile(),
                                        30 * 60,
                                        GET);
                                Map<String, String> map = new HashMap<>();
                                map.put("x-oss-process", dataBean.getParams().getXossprocess());
                                map.put("test", dataBean.getParams().getTest());
                                generatePresignedUrlRequest.setQueryParameter(map);
                                try {
                                    String url = oss.presignConstrainedObjectURL(generatePresignedUrlRequest);
                                    String urlShare = oss.presignConstrainedObjectURL(
                                            dataBean.getFile_bucket(),
                                            dataBean.getFile(),
                                            30 * 60
                                    );
                                    if (TextUtils.isEmpty(photoUrl)) photoUrl = url;
                                    dataBean.setThum(url);
                                    dataBean.setThumVideo(urlShare);
                                } catch (ClientException e) {
                                    e.printStackTrace();
                                }
                            } else if (2 == dataBean.getFile_type()) {
                                try {
                                    String urlVideo = oss.presignConstrainedObjectURL(
                                            dataBean.getFile_bucket(),
                                            dataBean.getFile(),
                                            30 * 60
                                    );
                                    String url = oss.presignConstrainedObjectURL(
                                            dataBean.getFile_bucket(),
                                            dataBean.getVideo_img(),
                                            60 * 60
                                    );
                                    if (TextUtils.isEmpty(videoUrl)) videoUrl = url;
                                    dataBean.setThum(url);
                                    dataBean.setThumVideo(urlVideo);
                                } catch (ClientException e) {
                                    e.printStackTrace();
                                }
                            }

                            if (!months.contains(m)) {
                                List<FamilyResCallbackBean.DataBeanX.DataBean> dataBeansList = new ArrayList<>();
                                dataBeansList.add(dataBean);
                                months.add(m);
                                maps.put(m, dataBeansList);
                            } else {
                                if (!maps.get(m).contains(dataBean)) {
                                    maps.get(m).add(dataBean);
                                }
                            }
                        }
                        monthAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    //删除文件
    public void deleteSecretFile(String fileStrs) {
        HTTPAPI.getInstance().deleteSecretFile(fileStrs, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(SecretResActivity.this, s);
                } else {
                    try {
                        ArrayList<String> ids = new ArrayList<>();
                        for (ImageBean ib : listItemLocations) {
                            String key = months.get(ib.getFirst());
                            listDataSecond.clear();
                            listDataSecond.addAll(maps.get(key));
                            for (FamilyResCallbackBean.DataBeanX.DataBean familyBean : listDataSecond) {
                                if (ib.getSecond() == familyBean.getId()) {
                                    if (listDataSecond.size() == 1) {
                                        maps.remove(key);
                                        ids.add(key);
                                    } else {
                                        maps.get(key).remove(familyBean);
                                    }
                                }
                            }
                        }

                        if (!ids.isEmpty()) {
                            for (String innerKey: ids) months.remove(innerKey);
                            ids.clear();
                        }

                        monthAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    fileIds.clear();
                    listItemLocations.clear();
                    strs = "";
                }
            }
        });
    }

    private void getSecretFileTotal() {
        HTTPAPI.getInstance().getSecretFileTotal(new StringCallback() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(SecretResActivity.this, s);
                } else {
                    FamilyFileTotalBean bean = GsonUtil.GsonToBean(s, FamilyFileTotalBean.class);
                    for (FamilyFileTotalBean.DataBean dataBean : bean.getData()) {
                        if (dataBean.getFile_type() == 1) {
                            photoHint = dataBean.getNum() + "";
                        } else if (2 == dataBean.getFile_type()) {
                            videoHint = dataBean.getNum() + "";
                        } else if (4 == dataBean.getFile_type()) {
                            textUrl = dataBean.getContent_intro();
                            textHint = dataBean.getNum() + "";
                        }
                    }

                    //初始化数据
                    initRecycler();
                }
            }
        });
    }


    public void secretToHome(String files) {
        HTTPAPI.getInstance().secretToHome(files, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("转移成功" + s);
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(SecretResActivity.this, s);
                } else {
                    ArrayList<String> ids = new ArrayList<>();
                    for (ImageBean ib : listItemLocations) {
                        String key = months.get(ib.getFirst());
                        listDataSecond.clear();
                        listDataSecond.addAll(maps.get(key));
                        for (FamilyResCallbackBean.DataBeanX.DataBean familyBean : listDataSecond) {
                            if (ib.getSecond() == familyBean.getId()) {
                                if (listDataSecond.size() == 1) {
                                    maps.remove(key);
                                    ids.add(key);
                                } else {
                                    maps.get(key).remove(familyBean);
                                }
                            }
                        }
                    }

                    if (!ids.isEmpty()) {
                        for (String innerKey: ids) months.remove(innerKey);
                        ids.clear();
                    }

                    monthAdapter.notifyDataSetChanged();

                    fileIds.clear();
                    listItemLocations.clear();
                    strs = "";
                }
            }
        });
    }

    private void downloadFile(String url, String type) {
        File appDir =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                        .getAbsoluteFile();
        if (!appDir.exists())
            //noinspection ResultOfMethodCallIgnored
            appDir.mkdir();

        String fileName = TextUtils.equals("image", type)
                ? "picture_" + System.currentTimeMillis() + ".jpg"
                : "video_" + System.currentTimeMillis() + ".mp4";

        HTTPAPI.getInstance().download(url, new FileCallback(
                appDir.getAbsolutePath(),
                fileName
        ) {
            @Override
            public void onBefore(BaseRequest request) {
                mDialog = new DowloadDialog(SecretResActivity.this);
                mDialog.show();
            }

            @Override
            public void onSuccess(File file, Call call, Response response) {
                //发送广播通知系统图库刷新数据
                Uri uri = Uri.fromFile(file);
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                ToastUtil.showToast("已保存到相册！");
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
                ToastUtil.showToast("文件下载失败！");
            }

            @Override
            public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                OkLogger.i("currentSize:" + currentSize);
                OkLogger.i("totalSize:" + totalSize);
                if (mDialog != null) mDialog.setProgress((int) (progress * 100));
            }

        });
    }

}
